import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import { isOnlineApp, programmeFlag } from '@/settings'

Vue.use(Router)
function h5Routes() {
  const context = require.context('./h5', true, /^\.\/.+\.js$/)
  const routes = []
  context.keys().forEach(key => {
    routes.push(...context(key).default)
  })
  routes.push({
    path: '*',
    redirect: '/404',
    name: 'NotFound'
  })
  return routes
}
const router = new Router({
  routes: h5Routes(),
  mode: isOnlineApp ? 'history' : 'hash', // 在线应用为 history ,离线应用为 hash
  base: isOnlineApp ? `${programmeFlag}/` : process.env.NODE_ENV === 'production' ? '' : '/H5/',
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else if (to.matched.every(e => e.path !== '/layout')) {
      return { x: 0, y: 0 }
    }
    return false
  }
})

const history = window.sessionStorage
history.clear()

let historyCount = history.getItem('count') * 1 || 0
history.setItem('/', 0)
let isPush = false
let endTime = Date.now()
const methods = ['push', 'go', 'replace', 'forward', 'back']

document.addEventListener('touchend', () => {
  endTime = Date.now()
})

methods.forEach(key => {
  const method = router[key].bind(router)
  router[key] = function(...args) {
    isPush = true
    method.apply(null, args)
  }
})

router.beforeEach((to, from, next) => {
  if (from.path !== to.path && from.meta.isHome === true && to.meta.isHome === true && to.params.bottomClick !== true) {
    window.nativeHandler('closeWeb')
  }

  store.commit('updateLoadingStatus', {
    isLoading: true
  })
  const toIndex = history.getItem(to.path)
  const fromIndex = history.getItem(from.path)

  if (toIndex) {
    if (!fromIndex || parseInt(toIndex, 10) > parseInt(fromIndex, 10) || (toIndex === '0' && fromIndex === '0')) {
      store.commit('updateDirection', {
        direction: 'forward'
      })
    } else {
      if (!isPush && (Date.now() - endTime) < 377) {
        store.commit('updateDirection', {
          direction: ''
        })
      } else {
        store.commit('updateDirection', {
          direction: 'reverse'
        })
      }
    }
  } else {
    ++historyCount
    history.setItem('count', to.meta.level || historyCount)
    to.path !== '/' && history.setItem(to.path, to.meta.level || historyCount)
    store.commit('updateDirection', {
      direction: 'forward'
    })
  }
  if (/\/http/.test(to.path)) {
    const url = to.path.split('http')[1]
    window.location.href = `http${url}`
  } else {
    next()
  }
})

router.afterEach((to, from) => {
  isPush = false
  document.body.style.overflow = 'initial'
  store.commit('updateLoadingStatus', {
    isLoading: false
  })
  window.scrollTo(0, 0)
})

export default router
